<?php

namespace App\Http\Controllers\Api;

use App\Models\Article;
use App\Models\EacooVillage;
use App\Models\PartyEms;
use App\Models\PartyUser;
use App\Models\Sms;
use App\Models\SystemRegion;
use App\Services\SensitiveWords;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;

class PartyController extends Controller
{
    //  接口请求
    protected $apiRequest = '';

    //  POST请求数据
    protected $apiPost = [];

    //  TOKEN
    protected $token = '';

    //  TOKEN中用户信息
    protected $tokenUser = '';

    //  地理位置信息【地区ID】
    protected $regionId = 0;


    public function __construct(Request $request)
    {

        $this->apiPost = $request->post();

        if (!auth()->user()) {

            $this->tokenUser = auth()->user();
        }

        $message = [
            'region_id.required' => '请输入地区参数',
            'region_id.integer' => '请输入数字字符的地区参数'
        ];

        $validator = Validator::make($this->apiPost, [
            'region_id' => ['required', 'integer'],
        ], $message);

        // 验证失败返回
        if ($validator->fails()) {
            return jsonError($validator->messages()->first());
        }

        // 核对是否存在该地区
        // $check = EacooVillage::villageCheck($request -> input('region_id'));


        $this->regionId = $request -> input('region_id');


    }


    /**
     * 党务 - 首页
     * @return false|string
     */
    public function homepage()
    {


        $party_user_select = 'id as party_user_id,avatar,identity';

        $party_users = PartyUser::getPartyUserByRegion($this->regionId, $party_user_select);

        $return_data = [
            'party_users' => $party_users,
        ];

        return jsonSuccess($return_data);
    }


    /**
     * 党务 - 党总支
     * @return false|string
     */
    public function partyUserList(Request $request)
    {

        $party_users = PartyUser::partyUsers($request);

        return jsonSuccess($party_users);
    }


    /**
     * 党务 - 写信
     * @return false|string
     */
    public function writeLetters()
    {
        #   数据
        $letters_data = [
            'ems_title' => $this->apiPost['ems_title'] ?? '',     #   信件标题
            'ems_type' => $this->apiPost['ems_type'] ?? '',       #   信件类别;意见建议1、申诉2、控告3、其他4
            'ems_open' => $this->apiPost['ems_open'] ?? '',       # 信件是否公开;公开1，否0
            'ems_content' => $this->apiPost['ems_content'] ?? '', #  信件内容
            'ems_writer' => $this->apiPost['ems_writer'] ?? '',   #   写信人名字
            'ems_sex' => $this->apiPost['ems_sex'] ?? '',         #  写信人性别;男1，女0
            'ems_address' => $this->apiPost['ems_address'] ?? '', #  写信人地址
            'ems_mobile' => $this->apiPost['ems_mobile'] ?? '',   #   写信人手机号
            'captcha' => $this->apiPost['captcha'] ?? '',         #   短信验证码
            'region_id' => $this->regionId ?? ''                  #   所属地区ID
        ];

        #  验证信息
        $message = [
            'ems_title.required' => '请输入信件标题',
            'ems_type.required' => '请选择信件类别',
            'ems_type.in' => '信件类别参数错误',
            'ems_open.required' => '请选择信件是否公开',
            'ems_open.in' => '信件是否公开参数错误',
            'ems_content.required' => '请输入信件内容',
            'ems_content.max' => '信件内容最多300字',
            'ems_writer.required' => '请输入写信人姓名',
            'ems_writer.between' => '请输入长度为2～6位的姓名',
            'ems_sex.required' => '请选择写信人性别',
            'ems_sex.in' => '写信人性别参数错误',
            'ems_address.required' => '请输入写信人地址',
            'ems_mobile.required' => '请输入写信人手机号码',
            'ems_mobile.regex' => '写信人手机号码格式错误',
            'captcha.required' => '请输入短信验证码',
            'captcha.regex' => '请输入4位数字的验证码',
        ];

        //  验证器验证
        $validator = Validator::make($letters_data, [
            'ems_title' => ['required'], #   信件标题
            'ems_type' => ['required', Rule::in(1, 2, 3, 4)], #   信件类别;意见建议1、申诉2、控告3、其他4
            'ems_open' => ['required', Rule::in(0, 1)], # 信件是否公开;公开1，否0
            'ems_content' => ['required', 'max:300'], #  信件内容
            'ems_writer' => ['required', 'between:2,6'], #   写信人名字
            'ems_sex' => ['required', Rule::in(0, 1)], #  写信人性别;男1，女0
            'ems_address' => ['required',], #  写信人地址
            'ems_mobile' => ['required', 'regex:/^[1](([3][0-9])|([4][5-9])|([5][0-3,5-9])|([6][5,6])|([7][0-8])|([8][0-9])|([9][1,8,9]))[0-9]{8}$/'],  #   写信人手机号
            'captcha' => ['required', 'regex:/^[0-9]{4}$/'], #   短信验证码
        ], $message);

        //  验证器返回失败
        if ($validator->fails()) {
            return jsonError($validator->messages()->first());
        }


        $bad_word = SensitiveWords::getBadWord($this->apiPost['ems_content']);
        if (!empty($bad_word)) {
            return jsonError('请勿使用敏感词：'.current($bad_word));
        }

        //  短信验证码验证
        if (!Sms::check($this->apiPost['captcha'], $this->apiPost['ems_mobile'], 'WRITE_LETTERS')) {
            return jsonError(4003);
        }


        $result = PartyEms::create($letters_data);
        if ($result) {

            return jsonSuccess(2007);
        } else {
            return jsonError( 4023);
        }

    }


    /**
     * 党务 - 党总支
     * @return false|string
     */
    public function partyArticlesList()
    {
        $category_id = $this->apiPost['category_id'] ?? 0;
        $page_num = $this->apiPost['page_num'] ?? 1;
        $page_size = $this->apiPost['page_size'] ?? 10;
        $party_articles_select = 'id as articles_id,article_title,content,list_img,imgs,created_at,admin_id';

        $party_articles = Article::getPartyArticlesPaginateByRegion($this->regionId, $category_id, $page_num, $page_size, $party_articles_select);

        return jsonSuccess($party_articles);
    }
}
